/**
 * @author: 子龙
 */
package com.fzl.lotterysystem.controller;

import com.fzl.lotterysystem.common.pojo.CommonResult;
import com.fzl.lotterysystem.common.utils.JacksonUtil;
import com.fzl.lotterysystem.controller.param.DrawPrizeParam;
import com.fzl.lotterysystem.controller.param.ShowWinningRecordsParam;
import com.fzl.lotterysystem.controller.result.WinningRecordResult;
import com.fzl.lotterysystem.service.DTO.WinningRecordDTO;
import com.fzl.lotterysystem.service.impl.DrawPrizeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/draw")
public class DrawPrizeController {
    @Autowired
    private DrawPrizeServiceImpl drawPrizeService;
    @RequestMapping("/prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam drawPrizeParam) {
        log.info("drawPrize={}", drawPrizeParam);
        drawPrizeService.drawPrize(drawPrizeParam);
        return CommonResult.success(true);
    }

    @RequestMapping("/showWinning")
    public  CommonResult<List<WinningRecordResult>> WinningRecords(
            @Validated @RequestBody ShowWinningRecordsParam param) {
        log.info("showWinning={}", JacksonUtil.writeValueAsString(param));
        List<WinningRecordDTO> winningRecordDTOList= drawPrizeService.getRecords(param);

        return CommonResult.success(convertToWinningRecordResult(winningRecordDTOList));
    }

    private List<WinningRecordResult> convertToWinningRecordResult(
            List<WinningRecordDTO> winningRecordDTOList) {
        if (CollectionUtils.isEmpty(winningRecordDTOList)) {
            return Arrays.asList();
        }

        return winningRecordDTOList.stream()
                .map(winningRecordDTO ->{
                    WinningRecordResult winningRecordResult = new WinningRecordResult();
                    winningRecordResult.setWinnerId(winningRecordDTO.getWinnerId());
                    winningRecordResult.setWinnerName(winningRecordDTO.getWinnerName());
                    winningRecordResult.setPrizeName(winningRecordDTO.getPrizeName());
                    winningRecordResult.setPrizeTier(winningRecordDTO.getPrizeTier().getMessage());
                    winningRecordResult.setWinningTime(winningRecordDTO.getWinningTime());

                    return winningRecordResult;
                }).collect(Collectors.toList());
    }
}